package cn.edu.nju.software.android.adapter;

import java.util.ArrayList;

import me.maxwin.view.IListviewCallback;

import cn.edu.nju.software.android.activity.CommentActivity;
import cn.edu.nju.software.android.activity.DetailedUserActivity;
import cn.edu.nju.software.android.activity.DetailedWeiboActivity;
import cn.edu.nju.software.android.activity.MainActivity;
import cn.edu.nju.software.android.activity.PictureActivity;
import cn.edu.nju.software.android.activity.R;
import cn.edu.nju.software.android.activity.RetweetActivity;
import cn.edu.nju.software.android.model.Status;
import cn.edu.nju.software.android.model.User;
import cn.edu.nju.software.android.util.AsyncImageLoader;
import cn.edu.nju.software.android.util.DateHelper;
import cn.edu.nju.software.android.util.ImageUtil;
import cn.edu.nju.software.android.util.LocalFileHelper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class TimelineListViewAdapter extends ArrayAdapter<Status> {
	private final Context context;
	private IListviewCallback callback;
	private ArrayList<Status> statuses = new ArrayList<Status>();
	private int pageNum = 0;
	private String weiboFileName = "content.weibo";

	private Handler failureHandler = new Handler(){
		public void handleMessage(Message msg) {
			Toast.makeText(context, "WIFI没有打开", Toast.LENGTH_SHORT).show();
		}
	};
	
	private Handler refreshHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			notifyDataSetChanged(); // 发送消息通知ListView更新
			Toast.makeText(context, "刷新成功", Toast.LENGTH_SHORT).show();
			callback.onComplete();
			callback.resetToTopRow();
			if(pageNum == 1)
				callback.enableLoadFunction();
		}
	};

	private Handler loadHandler = new Handler(){
		public void handleMessage(Message msg) {
			notifyDataSetChanged(); // 发送消息通知ListView更新
			callback.onComplete();
			pageNum++;
			if (pageNum >= 5) {
				callback.disableLoadFunction();
			} else {
				callback.enableLoadFunction();
			}
		}
	};

	@SuppressWarnings("unchecked")
	public TimelineListViewAdapter(Context context, IListviewCallback callback) {
		super(context, R.layout.listview_weibo_original);
		this.context = context;
		this.callback = callback;
		ArrayList<Status> loadedFile = (ArrayList<Status>) LocalFileHelper
				.loadObjectsListFromFile(context, weiboFileName);
		if (loadedFile != null)
			statuses = loadedFile;
		else {
			getNewestStatuses();
			pageNum++;
		}
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final Status s = statuses.get(position);
		ImageView userImageView  = null;
		Button userTextView = null;
		TextView textView = null;
		ImageView subImageView = null;
		TextView dateTextView = null;
		TextView locationTextView = null;
		TextView sourceTextView = null;
		Button commentButton = null;
		Button retweetButton = null;

		Button originalUserNameButton = null;
		TextView retweetedTextView = null;
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if(s.getRetweetStatus() == null){
			convertView = inflater.inflate(R.layout.listview_weibo_original, parent, false);
			userImageView = (ImageView) convertView.findViewById(R.id.list_head_original);
			userTextView = (Button) convertView.findViewById(R.id.list_name_original);
			textView = (TextView) convertView.findViewById(R.id.list_content_original);
			subImageView = (ImageView) convertView.findViewById(R.id.list_picture_original);
			dateTextView = (TextView) convertView.findViewById(R.id.list_time_original);
			locationTextView = (TextView) convertView.findViewById(R.id.list_location_original);
			sourceTextView = (TextView)convertView.findViewById(R.id.list_source_original);
			commentButton = (Button) convertView.findViewById(R.id.list_comment_original);
			retweetButton = (Button) convertView.findViewById(R.id.list_retweet_original);
			try{
				setListViewListener(convertView,false,s);
			}catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			convertView = inflater.inflate(R.layout.listview_weibo_retweeted, parent, false);
			userImageView = (ImageView) convertView.findViewById(R.id.list_head_retweeted);
			userTextView = (Button) convertView.findViewById(R.id.list_name_retweeted);
			textView = (TextView) convertView.findViewById(R.id.list_link_retweeted);
			originalUserNameButton = (Button) convertView.findViewById(R.id.list_originalName_retweeted);
			retweetedTextView = (TextView) convertView.findViewById(R.id.list_content_retweeted);
			subImageView = (ImageView) convertView.findViewById(R.id.list_picture_retweeted);
			dateTextView = (TextView) convertView.findViewById(R.id.list_time_retweeted);
			locationTextView = (TextView) convertView.findViewById(R.id.list_location_retweeted);
			sourceTextView = (TextView)convertView.findViewById(R.id.list_source_retweeted);
			commentButton = (Button) convertView.findViewById(R.id.list_comment_retweeted);
			retweetButton = (Button) convertView.findViewById(R.id.list_retweet_retweeted);
			setListViewListener(convertView,true,s);
		}
		AsyncImageLoader userImageAsyLoader = new AsyncImageLoader();
		AsyncImageLoader subImageAsyLoader = new AsyncImageLoader();
		Drawable userCachedImage = userImageAsyLoader.loadDrawable(context, failureHandler, s
				.getUser().getProfileImageUrl(), userImageView,
				new AsyncImageLoader.ImageCallback() {
			@Override
			public void imageLoaded(Drawable imageDrawable,
					ImageView imageView, String imageUrl) {
				if(imageDrawable != null)
					imageView.setImageDrawable(ImageUtil.resizeProfilePic(imageDrawable));
			}
		},100, 100);
		if (userCachedImage == null) {
			userImageView.setImageResource(R.drawable.user);
		} else {
			userImageView.setImageDrawable(ImageUtil.resizeProfilePic(userCachedImage));
		}
		if (s.getRetweetStatus() != null) {
			User u = s.getRetweetStatus().getUser();
			if(u != null)
				originalUserNameButton.setText(u.getName());
			else
				originalUserNameButton.setText("");
			if (s.getRetweetStatus().getThumbnail_pic() != null) {
				Drawable subCachedImage = subImageAsyLoader.loadDrawable(
						context, failureHandler, s.getRetweetStatus().getThumbnail_pic(),
						subImageView, new AsyncImageLoader.ImageCallback() {
							@Override
							public void imageLoaded(Drawable imageDrawable,
									ImageView imageView, String imageUrl) {
								imageView.setImageDrawable(ImageUtil.resizeStatusPic(imageDrawable));
							}

						},1, 500);
				if (subCachedImage == null) {
					subImageView.setImageResource(R.drawable.loading);
				} else {
					subImageView.setImageDrawable(ImageUtil.resizeStatusPic(subCachedImage));
				}
			}else{
				LinearLayout layout = (LinearLayout) convertView.findViewById(R.id.retweet_layout);
				int index = layout.indexOfChild(subImageView);
				layout.removeViewAt(index);
			}
			retweetedTextView
			.setText(s.getRetweetStatus().getText());
			if(s.getGeo() != null){
				locationTextView.setText("维度:"+s.getGeo().getLatitude() + ",经度:" + s.getGeo().getLongtitude());
			}else{
				LinearLayout layout = (LinearLayout) convertView.findViewById(R.id.retweet_layout);
				int index = layout.indexOfChild(locationTextView);
				layout.removeViewAt(index);
			}
		}else{
			if (s.getThumbnail_pic() != null) {
				Drawable subCachedImage = subImageAsyLoader.loadDrawable(context,failureHandler,
						s.getThumbnail_pic(), subImageView,
						new AsyncImageLoader.ImageCallback() {
					@Override
					public void imageLoaded(Drawable imageDrawable,
							ImageView imageView, String imageUrl) {
						if(imageDrawable != null)
							imageView.setImageDrawable(ImageUtil.resizeStatusPic(imageDrawable));
					}

				},1, 500);
				if (subCachedImage == null) {
					subImageView.setImageResource(R.drawable.loading);
				} else {
					subImageView.setImageDrawable(ImageUtil.resizeStatusPic(subCachedImage));
				}
			}else{
				LinearLayout layout = (LinearLayout) convertView.findViewById(R.id.list_imageparent_layout);
				int index = layout.indexOfChild(subImageView);
				layout.removeViewAt(index);
			}
			if(s.getGeo() != null){
				locationTextView.setText("维度:"+s.getGeo().getLatitude() + ",经度:" + s.getGeo().getLongtitude());
			}else{
				LinearLayout layout = (LinearLayout) convertView.findViewById(R.id.list_imageparent_layout);
				int index = layout.indexOfChild(locationTextView);
				layout.removeViewAt(index);
			}
		}

		sourceTextView.setText("来自"+s.getSource());
		dateTextView.setText(DateHelper.getDateStr(s.getCreatedAt()));
		textView.setText(s.getText());
		userTextView.setText(s.getUser().getName());
		commentButton.setText("评论(" + s.getCommentsCount() + ")");
		retweetButton.setText("转发(" + s.getRepostsCount() + ")");
		userTextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, DetailedUserActivity.class);
				intent.putExtra("user", s.getUser());
				intent.putExtra("parent", MainActivity.class);
				context.startActivity(intent);
			}
		});
		convertView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, DetailedWeiboActivity.class);
				intent.putExtra("status", s);
				intent.putExtra("parent", MainActivity.class);
				context.startActivity(intent);
			}

		});
		return convertView;
	}


	public void getNewestStatuses() {
		long sinceId = 0;
		if (statuses.size() != 0)
			sinceId = statuses.get(0).getId();
		Status.downloadNewestStatus(sinceId, statuses, refreshHandler);
	}

	public void loadMoreStatuses() {
		long max_id = 0;
		if (statuses.size() != 0)
			max_id = statuses.get(statuses.size()-1).getId()-1;
		Status.downloadMoreStatus(max_id, statuses, loadHandler);
	}

	@Override
	public Status getItem(int position) {
		return statuses.get(position);
	}

	@Override
	public int getCount() {
		return statuses.size();
	}

	public void saveStatuses() {
		LocalFileHelper.saveObjects(
				context,
				new ArrayList<Status>(statuses.subList(0,
						(statuses.size() > 21) ? 21 : statuses.size())),
						weiboFileName);
	}

	private void setListViewListener(View view, final boolean isRetweet, final Status s) {
		view.setOnTouchListener(new OnTouchListener(){     
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					int touch = context.getResources().getColor(R.color.touch);
					v.setBackgroundColor(touch);
					if (isRetweet) {
						v.findViewById(R.id.list_name_retweeted).setBackgroundColor(touch);
						v.findViewById(R.id.retweet_layout).setBackgroundColor(touch);
						v.findViewById(R.id.list_originalName_retweeted).setBackgroundColor(touch);
						View child = v.findViewById(R.id.list_picture_retweeted);
						if(child != null)
							child.setBackgroundColor(touch);
					} else {
						v.findViewById(R.id.list_name_original).setBackgroundColor(touch);
						View child = v.findViewById(R.id.list_picture_original);
						if(child != null)
							child.setBackgroundColor(touch);
					}

				} else {
					int white = context.getResources().getColor(R.color.white);
					v.setBackgroundColor(white);
					if (isRetweet) {
						v.findViewById(R.id.list_name_retweeted).setBackgroundColor(white);
						v.findViewById(R.id.retweet_layout).setBackgroundColor(white);
						v.findViewById(R.id.list_originalName_retweeted).setBackgroundColor(white);
						View child = v.findViewById(R.id.list_picture_retweeted);
						if(child != null)
							child.setBackgroundColor(white);
					} else {
						v.findViewById(R.id.list_name_original).setBackgroundColor(white);
						View child = v.findViewById(R.id.list_picture_original);
						if(child != null)
							child.setBackgroundColor(white);
					}
				}
				return false;
			}
		});

		Button name = null;
		if (isRetweet) {
			name = (Button) view.findViewById(R.id.list_name_retweeted);
		} else {
			name = (Button) view.findViewById(R.id.list_name_original);
		}
		name.setOnTouchListener(new OnTouchListener(){     
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					((Button) v).setTextColor(context.getResources().getColor(R.color.gray));
				} else {
					((Button) v).setTextColor(context.getResources().getColor(R.color.black));
				}
				return false;
			}
		});

		ImageButton picture = null;
		if (isRetweet) {
			picture = (ImageButton) view.findViewById(R.id.list_picture_retweeted);
		} else {
			picture = (ImageButton) view.findViewById(R.id.list_picture_original);
		}
		if (picture != null) {
			picture.setOnTouchListener(new OnTouchListener(){     
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						Intent intent = new Intent(context, PictureActivity.class);
						if(!isRetweet)
							intent.putExtra("picture", s.getOriginal_pic());
						else{
							intent.putExtra("picture", s.getRetweetStatus().getOriginal_pic());
						}
						context.startActivity(intent);
					}
					return false;
				}
			});
		}

		Button comment = null;
		if (isRetweet) {
			comment = (Button) view.findViewById(R.id.list_comment_retweeted);
		} else {
			comment = (Button) view.findViewById(R.id.list_comment_original);
		}
		comment.setOnTouchListener(new OnTouchListener(){     
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					((Button) v).setTextColor(context.getResources().getColor(R.color.white));
				} else {
					((Button) v).setTextColor(context.getResources().getColor(R.color.black));
					Intent intent = new Intent(context, CommentActivity.class);
					intent.putExtra("isReply", false);
					intent.putExtra("status_id", s.getId());
					context.startActivity(intent);
				}
				return false;
			}
		});

		Button retweet = null;
		if (isRetweet) {
			retweet = (Button) view.findViewById(R.id.list_retweet_retweeted);
		} else {
			retweet = (Button) view.findViewById(R.id.list_retweet_original);
		}
		retweet.setOnTouchListener(new OnTouchListener(){     
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					((Button) v).setTextColor(context.getResources().getColor(R.color.white));
				} else {
					((Button) v).setTextColor(context.getResources().getColor(R.color.black));
					Intent intent = new Intent(context, RetweetActivity.class);
					intent.putExtra("status_id", s.getId());
					context.startActivity(intent);
				}
				return false;
			}
		});

	}
}
